import 'dart:io';
import 'dart:math';

import 'package:aliplayer_widget/utils/log_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yyshort/common/model/banner_model.dart';
import 'package:yyshort/common/model/recommend_list_model.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/common/routers/names.dart';
import 'package:yyshort/common/style/style.dart';
import 'package:yyshort/common/utils/network_provider.dart';
import 'package:yyshort/common/utils/utils.dart';
import 'package:yyshort/common/values/colors.dart';
import 'package:yyshort/common/widgets/app.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video/view.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video_page.dart';
import 'package:yyshort/pages/home/widgets/RecommendWidgetOne.dart';
import 'package:yyshort/pages/home/widgets/trendingWidget.dart';
import 'package:yyshort/pages/main/widgets/channels.dart';
import 'index.dart';
import 'package:flutter/services.dart'; // 新增：用于退出应用

// 改为有状态组件
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

// 在状态类中混入AutomaticKeepAliveClientMixin
class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  // 通过Get.find()获取控制器
  late HomeController controller;
  // 新增：用于两次返回判断的时间戳
  DateTime? _lastPressedAt;
  // 新增：两次点击的有效间隔（秒）
  final int _exitInterval = 1;

  @override
  void initState() {
    super.initState();
    controller = Get.find<HomeController>();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final screenHeight = MediaQuery.of(Get.context!).size.height;
    const snackbarHeight = 80.0;
    // 计算顶部边距：屏幕高度的一半 - Snackbar 高度的一半（实现垂直居中）
    final topMargin = (screenHeight - snackbarHeight) / 2;
    // 关键修改：用PopScope包裹Scaffold，实现返回监听
    return PopScope(
      canPop: !Platform.isAndroid, // 禁用默认返回行为
      // ignore: deprecated_member_use
      onPopInvoked: (bool didPop) async {
        if (!didPop) {
          // 处理返回逻辑
          final now = DateTime.now();
          if (_lastPressedAt == null ||
              now.difference(_lastPressedAt!) >
                  Duration(seconds: _exitInterval)) {
            _lastPressedAt = now;
            // 显示提示
            Get.snackbar(
              "",
              "",
              titleText: const SizedBox.shrink(),
              messageText: Center(
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxWidth: Get.width * 0.8),
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    decoration: BoxDecoration(
                      color: const Color.fromARGB(100, 0, 0, 0),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      "再按一次退出应用".tr,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                      softWrap: true, // 3. 允许换行
                      overflow: TextOverflow.visible,
                    ),
                  ),
                ),
              ),
              snackPosition: SnackPosition.TOP,
              duration: Duration(seconds: _exitInterval),
              backgroundColor: Colors.transparent,
              colorText: Colors.white,
              margin: EdgeInsets.only(top: topMargin),
              padding: const EdgeInsets.all(0),
              barBlur: 0, // 取消默认的背景模糊
              animationDuration: const Duration(milliseconds: 350),
            );
          } else {
            // 两次点击间隔有效，退出应用
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
          }
        }
      },
      child: Scaffold(
        appBar: _buildAppBar(),
        body: SafeArea(child: _buildView()),
      ),
    );
  }

  Widget _buildView() {
    return Obx(() {
      late NetworkService networkService = Get.find<NetworkService>();
      if (!networkService.isApiReachable) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.wifi_off, size: 100.w, color: Colors.grey),
              const SizedBox(height: 30),
              ElevatedButton(
                onPressed: () {
                  controller.coustomInit();
                },
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 30,
                    vertical: 12,
                  ),
                ),
                child: Text('重试'.tr),
              ),
            ],
          ),
        );
      } else {
        return controller.state.bannerList.isEmpty &&
                controller.state.recommendlist.isEmpty &&
                controller.state.trendingList.isEmpty
            ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [const Center(child: CircularProgressIndicator())],
                ),
              )
            : SmartRefresher(
                controller: controller.refreshController,
                onRefresh: controller.onRefresh,
                onLoading: controller.onLoading,
                enablePullDown: true,
                enablePullUp: true,
                child: SingleChildScrollView(
                  controller: controller.scrollController,
                  physics: const NeverScrollableScrollPhysics(),
                  child: Column(
                    children: <Widget>[
                      _buildBannerView(),
                      _buildRecommendView(),
                      SizedBox(height: 10.h),
                      MasonryGridWidget(
                        clickItem: (VideoModel) {
                          jumpTo_ShortVideoPage(VideoModel);
                        },
                      ),
                    ],
                  ),
                ),
              );
      }
    });
  }

  // 顶部导航（保持不变）
  AppBar _buildAppBar() {
    return transparentAppBar(
      title: Image.asset(
        'assets/images/app_title_logo.png',
        width: 73.w,
        height: 23.h,
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            Get.toNamed(AppRoutes.Search_Result);
          },
          child: Container(
            padding: EdgeInsets.all(12.w),
            child: Image.asset(
              'assets/images/yy_search.png',
              width: 22.w,
              height: 23.h,
              fit: BoxFit.contain,
            ),
          ),
        ),
      ],
    );
  }

  // 轮播图（保持不变）
  Widget _buildBannerView() {
    return Obx(
      () => controller.state.bannerList.isEmpty
          ? Container()
          : SizedBox(
              height: 270.w,
              width: ScreenUtil().screenWidth,
              child: Swiper(
                outer: true,
                autoplay: true,
                autoplayDelay: 3000,
                loop: true,
                fade: 0.8,
                viewportFraction: 0.5,
                scale: 0.7,
                layout: SwiperLayout.DEFAULT,
                itemWidth: 193.w,
                itemBuilder: (BuildContext context, int index) {
                  BannerModel banner = controller.state.bannerList[index];
                  return GestureDetector(
                    onTap: () {
                      switch (banner.type) {
                        case 1:
                          {
                            jumpTo_ShortVideoPage(banner);
                          }
                          break;
                        case 2:
                          break;
                        case 3:
                          break;
                      }
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey[800]!,
                            blurRadius: 1.w,
                            spreadRadius: 1.w,
                            offset: Offset(0, 1.w),
                          ),
                        ],
                        borderRadius: BorderRadius.circular(12.w),
                      ),
                      child: Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(12.w),
                            child: CachedNetworkImage(
                              imageUrl: banner.imgUrl!,
                              fit: BoxFit.fill,
                              width: 193.w,
                              height: 270.w,
                              errorWidget: (context, url, error) =>
                                  Icon(Icons.error),
                            ),
                          ),
                          Center(
                            child: Image.asset(
                              'assets/images/play.png',
                              width: 80.w,
                              height: 80.h,
                              fit: BoxFit.contain,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
                itemCount: controller.state.bannerList.length,
              ),
            ),
    );
  }

  // 推荐列表（保持不变）
  Widget _buildRecommendView() {
    return Obx(
      () => controller.state.recommendlist.isEmpty
          ? Container()
          : Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: controller.state.recommendlist.map<Widget>((
                RecommendModel item,
              ) {
                return RecommendWidgetOne(
                  recommendModel: item,
                  onPlayTap: (video) {
                    logd('组件 RecommendWidgetOne 点击视频标题:+ ${video.name}');
                    jumpTo_ShortVideoPage(video);
                  },
                );
              }).toList(),
            ),
    );
  }

  // 跳转逻辑（保持不变）
  jumpTo_ShortVideoPage(dynamic mode) {
    Get.to(
      () =>
          ShortVideoPage(preload: false, isforyouPage: false, superModel: mode),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
